package com.campus.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.app.mapper.UserMapper;
import com.campus.app.service.UsersService;
import com.campus.commons.entity.Student;
import com.campus.app.mapper.StudentMapper;
import com.campus.app.service.StudentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.commons.entity.User;
import com.campus.commons.utils.Error;
import com.campus.commons.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生信息表 服务实现类
 * </p>
 *
 * @author Rin
 * @since 2020-12-24
 */
@Service
@Validated
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentsService {
    /**
     * 学习部学生；
     */
    private  Map<String, Integer> map;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Result<List<Student>> getStudentByDeId(Integer deId) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper();
        queryWrapper.inSql("userId", "select u.id from user u where u.deId="+deId+" and roleId in (select r.id from role r where roleNature=0)");
        return Result.result(studentMapper.selectList(queryWrapper));
    }

    @Override
    public Integer existStudentByNameFromDepend(String name) {
        if (map==null||map.size()==0) {
            map= getStudentByDeId(1).getData().stream().collect(Collectors.toMap(Student::getStuname,Student::getId));
        }
        return map.get(name);
    }

    @Override
    public Student getStudentByUserId(Integer userId) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        return studentMapper.selectOne(queryWrapper);
    }

    @Override
    public Boolean existStudentByName(@NotNull String studentName) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("stuName", studentName);
        Integer count = studentMapper.selectCount(wrapper);
        return count >= 1;
    }

    @Override
    public boolean isDepartment(Integer studentId) {
        LambdaQueryWrapper<Student> queryWrapper = new QueryWrapper<Student>().lambda();
        queryWrapper.eq(Student::getUserid, "select u.id from user u where u.id=userId and u.deId<> -1");
        return studentMapper.selectOne(queryWrapper)!=null;
    }

    @Override
    public Result<List<Student>> getAll(int page, int limit) {
        Result<List<Student>> listResult = new Result<>();
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        Integer count = studentMapper.selectCount(queryWrapper);
        List<Student> studentAll_xml = studentMapper.getStudentAll_xml((page - 1) * limit, limit);
        listResult.setTotal(count);
        listResult.setSuccess(true);
        listResult.setData(studentAll_xml);
        return listResult;
    }

    @Override
    public Result<List<Student>> getCompoundQuery(int page, int limit, Student student, String start, String end) {
        Result<List<Student>> result = new Result<>();
        if (StringUtils.isEmpty(start)) {
            start = null;
        }
        if (StringUtils.isEmpty(end)) {
            end = null;

        }
        int RePage = (page - 1) * limit;
        List<Student> data = studentMapper.getCompoundQuery_xml(RePage, limit, student, start, end);
        result.setData(data);
        result.setSuccess(true);
        if (data.size() > 0) {
            result.setTotal(studentMapper.CompoundQuery_xmlCount(student, start, end));
            return result;
        }
        result.setTotal(0);
        return result;
    }

    @Override
    public Result<Student> getOneStudent(int id) {
        if (id <= 0) {
            return Result.error(Error.PARAMS_E3R, "id不能小于0");
        }
        return Result.verify(studentMapper.getOneStudent(id));
    }

    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Lazy
    @Autowired
    private UsersService userService;
    @Autowired
    private UserMapper userMapper;



    @Override
    public Result updateStudentAndUser(Student student, User user) {
        user.setId(student.getUserid());
         FunctionServerImpl.init();
        student.setClassid(FunctionServerImpl.classes.get(student.getClassName()));
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionTemplate);
        try {
            int i= userService.UpdateUser(user);
             i+= studentMapper.updateById(student);


            if (i != 2) {
                platformTransactionManager.rollback(transaction);
                return Result.error(Error.System, i);
            }
        } catch (Exception e) {

            platformTransactionManager.rollback(transaction);
            return Result.error(Error.Other_E1R, e.getMessage());
        }
        platformTransactionManager.commit(transaction);
        return Result.success(true);
    }

    @Override
    public Result delUserAndStudent(int studentId, int userId) {
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionTemplate);
        try {
            int count = studentMapper.deleteById(studentId);
            count += userMapper.deleteById(userId);
            if (count != 2) {
                platformTransactionManager.rollback(transaction);
                return Result.error(Error.System, count);
            }
        } catch (TransactionException e) {
            return Result.error(Error.Other_E1R, e.getMessage());
        }
        platformTransactionManager.commit(transaction);

        return Result.success(true);
    }

    @Override
    public Boolean checkIdCardByIdCad(String idCard) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("idCard", idCard);
        Integer count = studentMapper.selectCount(queryWrapper);
        return count == 1;
    }

    @Override
    public Result addStudentAndUser(User user, Student student) {
        user.setRoleid(-1);
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionTemplate);
        user.setCreatetime(null);
        new FunctionServerImpl().init();
        student.setClassid(FunctionServerImpl.classes.get(student.getClassName().toUpperCase()));
        try {
            int count = userMapper.insert(user);
            if (count == 0||user.getId()==0) {
                platformTransactionManager.rollback(transaction);
                return Result.error(Error.System, "用户插入失敗");
            }
            student.setUserid(user.getId());
            int i = studentMapper.insert(student);
            if (i == 0) {
                platformTransactionManager.rollback(transaction);
              return   Result.error(Error.System, "学生插入失败");
            }
        } catch (TransactionException e) {
            platformTransactionManager.rollback(transaction);
            return Result.error(Error.Other_E1R, e.getMessage());
        }
        platformTransactionManager.commit(transaction);


        return Result.success(true);
    }


}
